import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * transferTo
 * transferFrom 方法。用于两个通道中传递数据。
 */
public class FileChannelTest {

    public static void main(String[] args) throws Exception {

        RandomAccessFile randomAccessFile = new RandomAccessFile("d:/test.txt", "rw");
        FileChannel fileChannel = randomAccessFile.getChannel();

        RandomAccessFile toAccessFileChannel = new RandomAccessFile("d:/test1.txt", "rw");
        FileChannel toFileChannel = toAccessFileChannel.getChannel();

        RandomAccessFile file2 = new RandomAccessFile("d:/test2.txt", "rw");
        FileChannel file2Channel = file2.getChannel();

        long position = 0;
        long count = fileChannel.size();

        fileChannel.transferTo(position, count, toFileChannel);
        //toFileChannel.transferFrom(fileChannel,position,fileChannel.size());

        System.out.println("is over....");

        // 读取文件到buffer
        ByteBuffer buffer = ByteBuffer.allocate(48);
        int num;
        System.out.println("file size=" + count);

        while ((num = fileChannel.read(buffer)) != -1) {
            System.out.println("file read num=" + num);
            System.out.println(new String(buffer.array()));
            buffer.clear();
        }

        String hello = "hello FileChannle";
        buffer.put(hello.getBytes());

        buffer.flip();


        // 写入文件
        System.out.println("write some one=" + buffer);
        int writeNum = file2Channel.write(buffer);
        System.out.println("write some num=" + writeNum);


        fileChannel.close();
        toFileChannel.close();
        file2Channel.close();
    }

}
